#include "save.h"

void saveBMPHeaderAndDifference(BMP_FILE_HEADER fileHeader, 
		BMP_BITMAP_HEADER  bitmapHeader, unsigned char *bytes ,
		int size_bytes,FILE *output){
	
	fwrite(&fileHeader,sizeof(fileHeader),1,output);
	fwrite(&bitmapHeader,sizeof(bitmapHeader),1,output);
	
	saveHuffmanFrequency(output);
	
	fwrite(&size_bytes,sizeof(int),1,output);
	
	int x = fwrite((unsigned char *)bytes,sizeof(unsigned char),size_bytes+1,output);
    while( x < (size_bytes+1))
        x += fwrite((unsigned char *)bytes,sizeof(unsigned char),size_bytes+1,output);
        
    fflush(output);
}

void algorithmUncompressor(FILE *input,FILE *output){
	BMP bmp;
	int size_bytes;
	
	unsigned char *bytes = loadBMPHeaderAndHuffman(&bmp,input,&size_bytes);	

	fwrite(&bmp.fileHeader,sizeof(BMP_FILE_HEADER),1,output);
	fwrite(&bmp.bmpHeader,sizeof(BMP_BITMAP_HEADER),1,output);
	
	bmp.image = (char *)malloc(sizeof(char)*bmp.bmpHeader.BiSizeImag);	

	
	int size_strings = size_bytes*8;
	unsigned char strings[size_strings+1];

#ifdef DEBUG
	printf("%d\n",size_bytes);	
#endif

	convertBytestoString(strings,size_bytes,bytes);
	strings[size_strings] = '\0';
	
	int i,j,l;
	char finder[256];
	NODE n;
	char code = 0;	
	
	for( i=0,j=0,l=0;i<size_strings;i++){

		finder[j] = strings[i];
		finder[j+1] = '\0';
		n = decode(finder);
		
		if( n->c >= 0 ){
			j = 0;
			short int numBits = n->c;
			int diff = convertBytesToInt(strings,i+1,i+numBits); 
			code += diff;
			
			bmp.image[l++] = code;
			i += numBits;
		}
		else{
			j++;
		}
	}

	int x = fwrite(bmp.image,sizeof(char),bmp.bmpHeader.BiSizeImag,output);
	while( x < bmp.bmpHeader.BiSizeImag){
		x += fwrite(bmp.image,sizeof( char),bmp.bmpHeader.BiSizeImag-x,output);	
	}	

	fflush(output);
		
}
